#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

#include "serverTypes.h"

std::vector<A*> A::myObjects = std::vector<A*>();
std::vector<B*> B::myObjects = std::vector<B*>();
std::vector<C*> C::myObjects = std::vector<C*>();

Serializable* tryDeserialize(const std::vector<Serializable*>& prototypes, const std::string& value) {
	int i = 0;
	Serializable* result = NULL;
	while (i < prototypes.size() && result==NULL) {
		result = prototypes[i]->deserialize(value);
		++i;
	}
	return result;
}

void tryConsume(const std::vector<Consumer*> &consumers) {
	for (int i = 0; i < consumers.size(); ++i) {
		consumers[i]->consume();
	}
}

void init (std::vector<Serializable*> *prototypes, std::vector<Consumer*> *consumers) {
	prototypes->push_back(new A(0));
	prototypes->push_back(new B(0));
	prototypes->push_back(new C(0));
	
	consumers->push_back(new Aconsumer());
	consumers->push_back(new Bconsumer());
	consumers->push_back(new Cconsumer());
}

int main() {
	std::vector<Serializable*> prototypes;
	std::vector<Consumer*> consumers;
	
	init(&prototypes, &consumers);
	
	int sock, listener;
	struct sockaddr_in addr;
	char buf[1024];
	int bytes_read, bytes_sent;

	listener = socket(AF_INET, SOCK_DGRAM, 0);
	if (listener < 0) {
		perror("initialization of socket failed");
		exit(errno);
	}
	printf("listen\n");
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6006);
	addr.sin_addr.s_addr = INADDR_ANY;
	if (bind(listener, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		perror("bind failed");
		exit(errno);
	}
	printf("bind\n");
	struct sockaddr from_addr;
	int addr_len = sizeof(from_addr);
	while (1) {
		bytes_read = recvfrom(listener, (void *)buf, 1024, 0, &from_addr, (socklen_t*)&addr_len);
		if (bytes_read < 0) {
			perror("read failed");
			exit(errno);	
		}
		tryDeserialize(prototypes, std::string(buf));
		tryConsume(consumers);
	}
	close(sock);
	return 0;
}
